// API接口管理
const API_BASE_URL = 'http://localhost:8081';

const api = {
    // 用户认证相关
    auth: {
        // 登录
        login: (data) => fetch(`${API_BASE_URL}/auth/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(res => res.json()),

        // 注册
        register: (data) => fetch(`${API_BASE_URL}/auth/register`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(res => res.json()),

        // 退出登录
        logout: () => fetch(`${API_BASE_URL}/auth/logout`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        }).then(res => res.json())
    },

    // 用户相关
    user: {
        // 获取用户信息
        getProfile: () => fetch(`${API_BASE_URL}/user/profile`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        }).then(res => res.json()),

        // 更新用户信息
        updateProfile: (data) => fetch(`${API_BASE_URL}/user/profile`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify(data)
        }).then(res => res.json()),

        // 修改密码
        changePassword: (data) => fetch(`${API_BASE_URL}/user/password`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify(data)
        }).then(res => res.json())
    },

    // 咨询相关
    consultation: {
        // 获取可预约时间
        getAvailableTimes: (therapistId) => fetch(`${API_BASE_URL}/consultation/available-times/${therapistId}`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        }).then(res => res.json()),

        // 创建预约
        createAppointment: (data) => fetch(`${API_BASE_URL}/consultation/appointments`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify(data)
        }).then(res => res.json()),

        // 获取预约列表
        getAppointments: () => fetch(`${API_BASE_URL}/consultation/appointments`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        }).then(res => res.json()),

        // 取消预约
        cancelAppointment: (appointmentId) => fetch(`${API_BASE_URL}/consultation/appointments/${appointmentId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        }).then(res => res.json())
    },

    // 咨询师相关
    therapist: {
        // 获取咨询师列表
        getList: (params) => fetch(`${API_BASE_URL}/therapist/list?${new URLSearchParams(params)}`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        }).then(res => res.json()),

        // 获取咨询师详情
        getDetail: (id) => fetch(`${API_BASE_URL}/therapist/${id}`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        }).then(res => res.json()),

        // 更新咨询师信息
        updateProfile: (data) => fetch(`${API_BASE_URL}/therapist/profile`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify(data)
        }).then(res => res.json()),

        // 更新排班信息
        updateSchedule: (data) => fetch(`${API_BASE_URL}/therapist/schedule`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify(data)
        }).then(res => res.json())
    }
};

// 添加请求拦截器
axios.interceptors.request.use(config => {
    // 除了登录接口外,其他请求都需要带上token
    if (!config.url.includes('/login')) {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        } else {
            // 如果没有token就跳转到登录页
            window.location.href = '/login.html';
            return Promise.reject('No token found');
        }
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// 添加响应拦截器 
axios.interceptors.response.use(
    response => {
        // 2xx 范围内的状态码都会触发该函数。
        return response;
    },
    error => {
        // 超出 2xx 范围的状态码都会触发该函数。
        if (error.response && (error.response.status === 401 || error.response.data.code === 401)) {
            console.log('Token验证失败，跳转登录页');
            // 清除token
            localStorage.removeItem('token');
            // 跳转到登录页
            window.location.href = '/login.html';
            return Promise.reject(error);
        }
        return Promise.reject(error);
    }
);

// 错误处理
const handleError = (error) => {
    console.error('API Error:', error);
    alert(error.message || '请求失败，请稍后重试');
    throw error;
};

// 导出API
export default api; 